package com.untrance.shop.core.service.bean;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.repackaged.com.google.common.base.Preconditions;
import com.untrance.shop.core.dao.ImageDao;
import com.untrance.shop.core.service.ImageService;
import com.untrance.shop.model.Image;

/**
 * @author eugene zadyra
 */
@Service("imageService")
public class ImageServiceBean implements ImageService {
	@Autowired
	private ImageDao imageDao;

	@Override
	public byte[] getImageByName(String name) {
		Image image = imageDao.findImageByName(name);
		if (image != null && image.getImage() != null) {
			return image.getImage().getBytes();
		}else{
			return null;
		}
	}
	
	@Override
	public Image saveImage(String name, byte[] file) {
		Preconditions.checkNotNull(file, "File can not be NULL");
		Preconditions.checkNotNull(name, "Name can not be NULL");
		Image image = new Image(name, new Blob(file));
		imageDao.add(image);
		return image;
	}

	@Override
	public byte[] getImageByKey(Key key) {
		Image image = imageDao.find(key);
		if (image != null && image.getImage() != null) {
			return image.getImage().getBytes();
		}else{
			return null;
		}
	}

	@Override
	public List<Key> getAdditionalImagesByProductKey(Key productKey) {
		return imageDao.findAdditionalImagesByProductKey(productKey);
	}

}
